package cn.jimmie.learn.nattyfragmentplugin;

import android.annotation.SuppressLint;
import android.app.Application;
import android.os.Build;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * function :
 *
 * <p> Create Time:  2019年02月21日 15:25 </p>
 * <p> @author Jimmie.Qian  </p>
 */
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
//        SecurityManager sm = new SecurityManager();
//        System.setSecurityManager(sm);
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
                hookTest();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void hookTest() throws Exception {
        // 1. 获取 AMN 的gDefault对象
        @SuppressLint("PrivateApi")
        Class<?> amnClass = Class.forName("android.app.ActivityManagerNative");
        Field gDefaultField = amnClass.getDeclaredField("gDefault");
        gDefaultField.setAccessible(true);
        Object gDefault = gDefaultField.get(null);

        // 2. 获取 Singleton<IActivityManager> 的 mInstance 对象
        @SuppressLint("PrivateApi")
        Class<?> singletonClass = Class.forName("android.util.Singleton");
        Field mInstanceField = singletonClass.getDeclaredField("mInstance");
        mInstanceField.setAccessible(true);
        Object realActivityManager = mInstanceField.get(gDefault);

        // 3. 设置动态代理 的处理器
        InvocationHandler handler = new ActivityManagerHookHandler(realActivityManager);

        // 4. 生成动态代理对象
        @SuppressLint("PrivateApi")
        Class<?> iActivityManagerClass = Class.forName("android.app.IActivityManager");
        Object proxyActivityManager = Proxy.newProxyInstance(
                Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{iActivityManagerClass},
                handler
        );

        // 5. 替换 Singleton<IActivityManager> 的 mInstance 对象
        mInstanceField.set(gDefault, proxyActivityManager);
    }

    private static class ActivityManagerHookHandler implements InvocationHandler {
        private Object realAM;

        ActivityManagerHookHandler(Object realAM) {
            this.realAM = realAM;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("你被我 HOOK了 小心点....");
            Object result = method.invoke(realAM, args);
            System.out.println("HOOK HOOK HOOK...");
            return result;
        }
    }
}
